/*
 * Copyright (c) 2007 Michael Santos <michael.santos@gmail.com>
 *
 * Trivial, throttling, trickle fileystem
 *
 */

/*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2005  Miklos Szeredi <miklos@szeredi.hu>

This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/

#include <fuse.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>

#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <dirent.h>

#include <syslog.h>
#include <stdarg.h>

#include <sys/param.h>
#include <err.h>
#include <assert.h>

#include <time.h>

#include <errno.h>
#include <sys/sysctl.h>

#include "tfs.h"
#include "tfs_common.h"

#define PERIOD      1

struct TFS_POOL *pool_head = NULL;

size_t tfs_throttle(u_int32_t op, size_t size);
int tfs_check(u_int32_t op, struct TFS_POOL *pl);
int tfs_pid(char *re, pid_t pid);

#define MINBW 1

#define CACHESZ     32
pid_t pidcache[CACHESZ];
u_int32_t pidcounter = 0;

    size_t
tfs_throttle(u_int32_t op, size_t size)
{
    struct timeval now;
    ssize_t permit = 0;
    size_t min = size;

    struct TFS_POOL *pl = NULL;
    struct TFS_OP *rate = NULL;

    if (enforce == TFS_DISABLE)
        return (size);

    switch (op) {
        case TFS_WRITE:
        case TFS_READ:
            break;

        default:
            return (size);
    }

    (void)gettimeofday(&now, NULL);

    /*
    (void)fprintf(stdout, "tfs_throttle: --- ENTERING: size = %u\n", (u_int32_t)size);
    */

    for (pl = pool_head; pl; pl = pl->next) {
        rate = &pl->op[op];

        if (tfs_check(op, pl) < 0)
            continue;

        rate->match = 1;

        if (rate->limit == 0)
            rate->state = TFS_STATE_NOLIMIT;

        /*
        (void)fprintf(stdout, "tfs_throttle: MATCHED: TV_SEC: pool = %s, rate = %ld, now = %ld\n", pl->pool, (long int)rate->expiry.tv_sec, (long int)now.tv_sec);
        (void)fprintf(stdout, "tfs_throttle: MATCHED: TV_USEC: pool = %s, rate = %ld, now = %ld\n", pl->pool, (long int)rate->expiry.tv_usec, (long int)now.tv_usec);
        */

        if ( (rate->expiry.tv_sec < now.tv_sec) ||
                ( (rate->expiry.tv_sec == now.tv_sec) &&
                  (rate->expiry.tv_usec < now.tv_usec))) {
            rate->bytes = 0;
            rate->state = TFS_STATE_OK;
            /*
            (void)fprintf(stdout, "tfs_throttle: MATCHED: pool = %s, state = UNTHROTTLING\n", pl->pool);
            */
        }

        /*
        (void)fprintf(stdout, "tfs_throttle: MATCHED: pool = %s, state = %u\n", pl->pool, rate->state);
        */

        switch (rate->state) {
            case TFS_STATE_NOLIMIT:
                min = size;
                /*
                (void)fprintf(stdout, "tfs_throttle: CALC: NOLIMIT: pool = %s, min = %u\n", pl->pool, (u_int32_t)min);
                */
                break;

            case TFS_STATE_OK:
                rate->expiry.tv_sec = now.tv_sec + PERIOD;
                rate->expiry.tv_usec = now.tv_usec;
                /* fall through */

            case TFS_STATE_THROTTLED:
                {
                    /* XXX An application could request a large size to cause
                     * XXX an integer overflow, bypassing the throttling checks.
                     */
                    ssize_t tmp = rate->limit - (rate->bytes + size);

                    //assert( (rate->bytes > INT32_MAX) || (size > INT32_MAX) || (rate->bytes + size > INT32_MAX));

                    /*
                    (void)fprintf(stdout, "tfs_throttle: CALC: OK: pool = %s, limit = %u, bytes = %u, tmp = %d, size = %u, min = %u\n", pl->pool, (u_int32_t)rate->limit, (u_int32_t)rate->bytes, (int32_t)tmp, (u_int32_t)size, (u_int32_t)min);
                    */

                    if (tmp > 0)
                        permit = MIN(tmp, size);
                    else {
                        if (rate->limit > rate->bytes)
                            permit = rate->limit - rate->bytes;
                        else
                            permit = MINBW;

                        rate->state = TFS_STATE_THROTTLED;
                    }

                    min = MIN(permit, min);
                    /*
                    (void)fprintf(stdout, "tfs_throttle: CALC: OK: pool = %s, min = %u\n", pl->pool, (u_int32_t)min);
                    */
                }
                break;
        }
    }

    /*
    (void)fprintf(stdout, "tfs_throttle: FINAL: min = %u\n", (u_int32_t)min);
    */

    /* 3: Set the counters for each rule */
    for (pl = pool_head; pl; pl = pl->next) {
        rate = &pl->op[op];
        if (rate->match == 0)
            continue;

        rate->match = 0;
        rate->bytes += min;
        /*
        (void)fprintf(stdout, "tfs_throttle: FINAL: pool = %s, bytes = %u\n", pl->pool, (u_int32_t)rate->bytes);
        */
    }

    assert(min != 0);
    DD(min);
    return (min);
}

    int
tfs_check(u_int32_t op, struct TFS_POOL *pl)
{
    int i = 0;

#if CACHESZ > 0
    pid_t pid = fuse_get_context()->pid;

    for ( i = 0; i < CACHESZ; i++) {

        if (pidcache[pidcounter%CACHESZ] == pid)
            return (0);
    }
#endif

    if (strcmp(pl->pool, "global") == 0)
        return (0);

    if ( (fuse_get_context()->uid == pl->uid) ||
            (fuse_get_context()->gid == pl->gid) ||
            ( (pl->proc != NULL) && (tfs_pid(pl->proc, fuse_get_context()->pid) == 0))) {
        DV("matched", pl->pool);

#if CACHESZ > 0
        pidcache[pidcounter%CACHESZ] = pid;
        pidcounter++;
#endif
        return (0);
    }

    return (-1);
}

    int
tfs_pid(char *re, pid_t pid)
{   
    int i = 0;
    int mib[6] = {0, 0, 0, 0, 0, 0};
    size_t bufsz = 0;
    long numproc = 0;
    struct kinfo_proc *proc = NULL;

    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_ALL;

    for ( ; ; ) {
        if (sysctl(mib, 3, NULL, &bufsz, NULL, 0) != 0)
            err(EXIT_FAILURE, "buffer size");

        if ( (proc = (struct kinfo_proc *)calloc(sizeof(struct kinfo_proc *), bufsz)) == NULL)
            err(EXIT_FAILURE, "calloc");

        if (sysctl(mib, 3, proc, &bufsz, NULL, 0) == 0)
            break;
        else
            free(proc);
    }

    numproc = bufsz/sizeof(struct kinfo_proc);

    (void)fprintf(stdout, "numproc = %ld\n", numproc);

    for (i = 0; i < numproc; i++) {
        if ( (proc[i].kp_proc.p_pid == pid) &&
                (strcmp(proc[i].kp_proc.p_comm, re) == 0))
            return (0);
    }

    free (proc);
    return (1);
}

    char *
tfs_path(const char *path)
{
    char *realpath = NULL;

    if ( (realpath = calloc(MAXPATHLEN, 1)) == NULL)
        err(EXIT_FAILURE, NULL);

    D(realpath);

    (void)snprintf(realpath, MAXPATHLEN, "%s/%s", rootdir, path);
    return (realpath);
}

    int
tfs_getattr(const char *path, struct stat *stbuf)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    if ( (res = lstat(rp, stbuf)) != 0)
        res =  -errno;

    free(rp);
    return (res);
}

    int
tfs_open(const char *path, struct fuse_file_info *fi)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);
    if ( (fi->fh = open(rp, fi->flags)) < 0)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_opendir(const char *path, struct fuse_file_info *fi)
{
    int res = 0;
    char *rp = NULL;
    DIR *dp = NULL;

    D(path);

    rp = tfs_path(path);
    if ( (dp = opendir(rp)) == NULL)
        res = -errno;

    fi->fh = (unsigned long) dp;
    free (rp);
    return (res);
}

    inline DIR *
get_dirp(struct fuse_file_info *fi)
{   
    return (DIR *) (uintptr_t) fi->fh;
}


    int
tfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi)
{
    DIR *dp = get_dirp(fi);
    struct dirent *de = NULL;

    D(path);

    (void) path;
    seekdir(dp, offset);
    while ((de = readdir(dp)) != NULL) {
        struct stat st;

        (void)memset(&st, 0, sizeof(st));
        st.st_ino = de->d_ino;
        st.st_mode = de->d_type << 12;
        if (filler(buf, de->d_name, &st, telldir(dp)))
            break;
    }

    return 0;
}

    int
tfs_releasedir(const char *path, struct fuse_file_info *fi)
{
    DIR *dp = get_dirp(fi);

    D(path);

    (void) path;
    closedir(dp);
    return 0;
}


    int
tfs_read (const char *path, char * buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
    int res = 0;

    D(path);

    size = tfs_throttle(TFS_READ, size);

    (void) path;
    if ( (res = pread(fi->fh, buf, size, offset)) < 0)
        res = -errno;

    return (res);
}

    int
tfs_write (const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
    int res = 0;

    D(path);

    size = tfs_throttle(TFS_WRITE, size);

    (void) path;
    if ( (res = pwrite(fi->fh, buf, size, offset)) < 0)
        res = -errno;

    return (res);
}

    int
tfs_mknod(const char *path, mode_t mode, dev_t rdev)
{   
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    if (S_ISFIFO(mode))
        res = mkfifo(rp, mode);
    else
        res = mknod(rp, mode, rdev);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_mkdir(const char *path, mode_t mode)
{
    int res;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = mkdir(rp, mode);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_unlink(const char *path)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = unlink(rp);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_fgetattr(const char *path, struct stat *stbuf, struct fuse_file_info *fi)
{
    int res = 0;

    D(path);

    (void) path;

    res = fstat(fi->fh, stbuf);
    if (res == -1)
        res =  -errno;

    return (res);
}

    int
tfs_access(const char *path, int mask)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = access(rp, mask);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_readlink(const char *path, char *buf, size_t size)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = readlink(rp, buf, size - 1);
    if (res == -1)
        res =  -errno;
    else
        buf[res] = '\0';

    free(rp);
    return (res);
}

    int
tfs_rmdir(const char *path)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = rmdir(rp);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_symlink(const char *from, const char *to)
{
    int res = 0;
    char *rf = NULL;
    char *rt = NULL;

    D(from);
    D(to);

    rf = tfs_path(from);
    rt = tfs_path(to);

    res = symlink(rf, rt);
    if (res == -1)
        res = -errno;

    free(rf);
    free(rt);
    return (res);
}

    int
tfs_rename(const char *from, const char *to)
{
    int res = 0;
    char *rf = NULL;
    char *rt = NULL;

    D(from);
    D(to);

    rf = tfs_path(from);
    rt = tfs_path(to);

    res = rename(rf, rt);
    if (res == -1)
        res = -errno;

    free(rf);
    free(rt);
    return 0;
}

    int
tfs_link(const char *from, const char *to)
{
    int res = 0;
    char *rf = NULL;
    char *rt = NULL;

    D(from);
    D(to);

    rf = tfs_path(from);
    rt = tfs_path(to);

    res = link(rf, rt);
    if (res == -1)
        res = -errno;

    free(rf);
    free(rt);
    return 0;
}

    int
tfs_chmod(const char *path, mode_t mode)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = chmod(rp, mode);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_chown(const char *path, uid_t uid, gid_t gid)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = lchown(rp, uid, gid);

    free(rp);
    return (res < 0 ? -errno : res);
}

    int
tfs_truncate(const char *path, off_t size)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = truncate(rp, size);

    free(rp);
    return (res < 0 ? -errno : res);
}

    int
tfs_ftruncate(const char *path, off_t size, struct fuse_file_info *fi)
{
    int res = 0;

    (void) path;

    res = ftruncate(fi->fh, size);

    return (res < 0 ? -errno : res);
}

    int
tfs_utimens(const char *path, const struct timespec ts[2])
{
    int res = 0;
    char *rp = NULL;
    struct timeval tv[2];

    D(path);

    rp = tfs_path(path); 

    tv[0].tv_sec = ts[0].tv_sec;
    tv[0].tv_usec = ts[0].tv_nsec / 1000;
    tv[1].tv_sec = ts[1].tv_sec;
    tv[1].tv_usec = ts[1].tv_nsec / 1000;

    res = utimes(rp, tv);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_create(const char *path, mode_t mode, struct fuse_file_info *fi)
{
    int res = 0;
    char *rp = NULL;

    int fd = -1;

    D(path);

    rp = tfs_path(path);

    fd = open(rp, fi->flags, mode);
    if (fd == -1)
        res = -errno;
    else
        fi->fh = fd;

    free(rp);
    return (res);
}

    int
tfs_statfs(const char *path, struct statvfs *stbuf)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = statvfs(rp, stbuf);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_flush(const char *path, struct fuse_file_info *fi)
{
    int res = 0;

    D(path);

    (void) path;
    /* This is called from every close on an open file, so call the
       close on the underlying filesystem.  But since flush may be
       called multiple times for an open file, this must not really
       close the file.  This is important if used on a network
       filesystem like NFS which flush the data/metadata on close() */
    res = close(dup(fi->fh));
    if (res == -1)
        res = -errno;

    return (res);
}

    int
tfs_release(const char *path, struct fuse_file_info *fi)
{
    (void) path;
    close(fi->fh);

    return 0;
}

int
tfs_fsync(const char *path, int isdatasync,
        struct fuse_file_info *fi)
{
    int res;
    (void) path;

#ifndef HAVE_FDATASYNC
    (void) isdatasync;
#else
    if (isdatasync)
        res = fdatasync(fi->fh);
    else
#endif
        res = fsync(fi->fh);
    if (res == -1)
        return -errno;

    return 0;
}

#ifdef HAVE_SETXATTR
/* xattr operations are optional and can safely be left unimplemented */
    int
tfs_setxattr(const char *path, const char *name, const char *value, size_t size, int flags)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);
    res = lsetxattr(rp, name, value, size, flags);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_getxattr(const char *path, const char *name, char *value, size_t size)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = lgetxattr(rp, name, value, size);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_listxattr(const char *path, char *list, size_t size)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = llistxattr(rp, list, size);
    if (res == -1)
        res = -errno;

    free(rp);
    return (res);
}

    int
tfs_removexattr(const char *path, const char *name)
{
    int res = 0;
    char *rp = NULL;

    D(path);

    rp = tfs_path(path);

    res = lremovexattr(rp, name);
    if (res == -1)
        res = -errno;

    free(rp);

    return (res);
}
#endif /* HAVE_SETXATTR */

#if 0
    int
tfs_lock(const char *path, struct fuse_file_info *fi, int cmd, struct flock *lock)
{
    (void) path;

    return ulockmgr_op(fi->fh, cmd, lock, &fi->lock_owner,
            sizeof(fi->lock_owner));
}
#endif 

static struct fuse_operations tfs_oper = {
    .getattr	= tfs_getattr,
    .open		= tfs_open,
    .read		= tfs_read,
    .write		= tfs_write,
    .opendir	= tfs_opendir,
    .readdir	= tfs_readdir,
    .releasedir	= tfs_releasedir,
    .mknod		= tfs_mknod,
    .mkdir		= tfs_mkdir,
    .unlink		= tfs_unlink,
    .fgetattr	= tfs_fgetattr,
    .access		= tfs_access,
    .readlink	= tfs_readlink,
    .rmdir		= tfs_rmdir,
    .symlink	= tfs_symlink,
    .rename		= tfs_rename,
    .chmod		= tfs_chmod,
    .link		= tfs_link,
    .chown		= tfs_chown,
    .truncate	= tfs_truncate,
    .ftruncate	= tfs_ftruncate,
    .utimens	= tfs_utimens,
    .create		= tfs_create,
    .statfs		= tfs_statfs,
    .flush		= tfs_flush,
    .release	= tfs_release,
    .fsync		= tfs_fsync,
#ifdef HAVE_SETXATTR
    .setxattr	= tfs_setxattr,
    .removexattr	= tfs_removexattr,
    .listxattr	= tfs_listxattr,
    .getxattr	= tfs_getxattr,
#endif /* HAVE_SETXATTR */
#if 0
    .lock		= tfs_lock,
#endif
};

    int
main(int argc, char *argv[])
{
    struct stat sb;
    char *path = NULL;
    char *disable = NULL;

    (void)umask(0);
    (void)memset(&sb, 0, sizeof(sb));

    disable = getenv(TFS_ENFORCE_CHECKS);
    if ( (disable != NULL) && \
            ((u_int8_t)atoi(disable) != TFS_ENABLE)) {
        enforce = TFS_DISABLE;
        DV("Disabling checks", disable);
    }

    if (argc > 1) {
        if ( (path = strchr(argv[1], ':')) == NULL) {
            warnx("Specify mount point using format: <fuse directory>:<local directory>");
        }
        else {
            *path++ = '\0';

            if ( (stat(path, &sb) < 0) || !(sb.st_mode & S_IFDIR))
                err(EXIT_FAILURE, "Invalid parent directory: %s", path);

            (void)snprintf(rootdir, MAXPATHLEN, "%s", path);
        }
    }

    pool_head = tfs_conf(NULL);

    return fuse_main(argc, argv, &tfs_oper, NULL);
}

